package com.example.mydemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.mydemo.impl.MyFunction;
import com.example.mydemo.utils.CheckPermissionS;


public class MainActivity extends AppCompatActivity {

//    private static final String[] Permission_MSG = new String[]{
//            Manifest.permission.SEND_SMS,//发短信权限
//            Manifest.permission.READ_SMS,//读短信权限
//            Manifest.permission.RECEIVE_SMS,//接收短信权限
//    };
//    private static final String[] Permission_Phone = new String[]{
//            Manifest.permission.READ_PHONE_STATE,//读取电话状态权限
//            Manifest.permission.READ_CALL_LOG,//读取电话记录
//            Manifest.permission.READ_CONTACTS,//读取联系人
//    };
    private static final String[] PERMISSION_ALL = new String[]{
            Manifest.permission.SEND_SMS,//发短信权限
            Manifest.permission.READ_SMS,//读短信权限
            Manifest.permission.RECEIVE_SMS,//接收短信权限
            Manifest.permission.READ_PHONE_STATE,//读取电话状态权限
            Manifest.permission.READ_CALL_LOG,//读取电话记录
            Manifest.permission.READ_CONTACTS,//读取联系人
    };
    private static final int REQUEST_All = 3;//全部权限
    private Boolean isGrant = false;//获取权限
    private ImageButton start;
    private ImageButton hitorylist;
    private SmsReceiver smsReceiver;//短信监听
    private MissedCallReceiver missedCallReceiver;//短信监听

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListenner();
        //ContentObserve监听
        createReceiver();//创建监听对象
        //动态获取权限
        GetGrant();
        //注册监听器
        registerMyReceiver();
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        String temp=telephonyManager.getLine1Number();
        Log.d("TAG", "获取手机号码：" + temp);
    }

    private void initView() {
        start = findViewById(R.id.start);
        hitorylist = findViewById(R.id.hitorylist);

    }

    private void initListenner() {
        //功能开启按钮
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isGrant) {
                    if (!CheckPermissionS.startObserver) {
                        //口令校验
                        showDialog();
                    } else {
                        //再次点击为关闭监听
                        Toast.makeText(MainActivity.this, "功能已关闭", Toast.LENGTH_SHORT).show();
                        start.setImageResource(R.drawable.close);
                        CheckPermissionS.startObserver = false;
                    }

                } else {
                    //如果用户并未给权限点击按钮仍需申请权限
                    GetGrant();
                }
            }

        });
        //历史记录按钮
        hitorylist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isGrant) {
                    Intent intent = new Intent(MainActivity.this, ShowListActivity.class);
                    startActivity(intent);
                } else {
                    GetGrant();
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //grantResults就代表用户是否选择授权
        switch (REQUEST_All) {
            case REQUEST_All:
                if (CheckPermissionS.checkGrant(grantResults)) {
                    Log.d("TAG", "获取全部权限成功！");
                    isGrant = true;
                } else {
                    Toast.makeText(MainActivity.this, "获取全部权限失败！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    //显示口令验证对话框
    private void showDialog() {
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog, null);
        //获取到上下文中的组件
        EditText passwordEditText = dialogView.findViewById(R.id.password_edit_text);
        Button cancelButton = dialogView.findViewById(R.id.cancel_button);
        Button confirmButton = dialogView.findViewById(R.id.confirm_button);
        //设置对应的相应事件
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        cancelButton.setOnClickListener(
                v -> {
                    dialog.dismiss();
                    Toast.makeText(MainActivity.this, "取消", Toast.LENGTH_SHORT).show();
                }
        );

        confirmButton.setOnClickListener(v -> {
            String password = passwordEditText.getText().toString();
            if (validatePassword(password)) {
                Toast.makeText(MainActivity.this, "密码正确", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
                //开始监听
                //启动监听
                CheckPermissionS.startObserver = true;
                start.setImageResource(R.drawable.open);
                Log.d("MainActivity", "开始监听");
            } else {
                Toast.makeText(MainActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
            }
        });

        dialog.show();
    }

    public void registerMyReceiver() {
        // 创建BroadcastReceiver实例
        if (smsReceiver != null) {
            // 创建IntentFilter并注册接收器
            IntentFilter smsfilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
            registerReceiver(smsReceiver, smsfilter);
        }
        if (missedCallReceiver != null) {
            // 创建IntentFilter并注册接收器
            //注册意图过滤器，帮我们过滤广播
            IntentFilter filter = new IntentFilter();
            filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
            registerReceiver(missedCallReceiver, filter);
        }
    }

    public void createReceiver() {
        //化创建SmsReceiver missedCallReceiver
        smsReceiver = new SmsReceiver(this, new MyFunction() {
            @Override
            public void apply() {
                // 确保在主线程上执行UI操作
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (CheckPermissionS.startObserver) {
                            // 启动监听
                            start.setImageResource(R.drawable.open);
                            Log.d("TAG", "开始监听");
                        } else {
                            // 取消注册
                            start.setImageResource(R.drawable.close);
                            Log.d("TAG", "取消监听");
                        }
                    }
                });
                //这里还可以使用组件的post方法会直接切换到主线程
                // start.post(new Runnable() {})
            }
        });
        missedCallReceiver = new MissedCallReceiver(this);
    }

    //取消注册监听
    public void unregisterMyReceiver() {
        if (smsReceiver != null) {
            unregisterReceiver(smsReceiver);
            smsReceiver = null;
        }
        if (missedCallReceiver != null) {
            unregisterReceiver(missedCallReceiver);
            missedCallReceiver = null;
        }
    }

    //验证密码
    private Boolean validatePassword(String password) {
        return password.equals("1234"); //
    }

    //获取权限
    private void GetGrant() {
        if (CheckPermissionS.checkPermissions(this, PERMISSION_ALL, REQUEST_All)) {
            isGrant = true;
            Log.d("TAG", "获取全部权限成功！");
        }
    }

    //退出时取消注册监听
    // 确保在销毁时取消注册接收器
    @Override
    protected void onStop() {
        super.onStop();
        //取消注册contentobserver
        // 确保在销毁时取消注册接收器
        unregisterMyReceiver();
    }
}